package com.zhentao.equipment.controller;

import com.zhentao.equipment.mapper.DeviceStatusLogMapper;
import com.zhentao.pojo.DeviceStatusLog;
import com.zhentao.util.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.util.Date;

/**
 * 心跳上报接口：设备或接入网关调用
 */
@RestController
@RequestMapping("/api/devices")
@CrossOrigin(origins = "*")
public class DeviceHeartbeatController {

    @Autowired(required = false)
    private StringRedisTemplate redis;

    @Autowired
    private DeviceStatusLogMapper logMapper;

    private String k(Long deviceId) { return "device:online:" + deviceId; }

    /**
     * 上报心跳（写入Redis）。如果由离线切换为在线，记录一条状态日志。
     * ttlMinutes：心跳过期时间（默认45分钟）
     */
    @PostMapping("/{id}/heartbeat")
    public ResultVo heartbeat(@PathVariable("id") Long deviceId,
                              @RequestParam(required = false) Integer ttlMinutes) {
        if (redis == null) return ResultVo.error(400, "Redis未配置，无法记录心跳");
        long now = System.currentTimeMillis();
        String key = k(deviceId);
        String last = redis.opsForValue().get(key);
        boolean wasOnline = false;
        if (last != null) {
            // 认为30分钟内有心跳则在线
            wasOnline = now - Long.parseLong(last) <= 30 * 60 * 1000L;
        }
        redis.opsForValue().set(key, String.valueOf(now), Duration.ofMinutes(ttlMinutes == null ? 45 : ttlMinutes));

        // 若此前判定为离线，现在收到心跳，记录“上线”日志
        if (!wasOnline) {
            DeviceStatusLog log = new DeviceStatusLog();
            log.setDeviceId(deviceId);
            log.setOldStatus(2); // 离线
            log.setNewStatus(1); // 在线
            log.setChangeReason("心跳上报");
            log.setCreateTime(new Date());
            logMapper.insert(log);
        }
        return ResultVo.success();
    }
}





